﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using qltscd.Models;
using qltscd.Models.ScreenClient;
using qltscd.Contansts;
using Telerik.Web.Mvc;
using qltscd.Helper;
using CrystalDecisions.CrystalReports.Engine;
using System.IO;
using CrystalDecisions.Shared;
using System.Text;
using System.Web.Routing;

namespace qltscd.Controllers
{
    public class DanhMucNhomNguoiDungController : BaseController
    {
        protected override void OnActionExecuting (ActionExecutingContext filterContext) {
            base.OnActionExecuting(filterContext);
            if (SessionHelper.QuyenNhom[qltscd.Contansts.KeyContansts.QuyenDanhMuc] == '0') {
                filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new {
                    controller = "KhongCoQuyen",
                    action = "Index"
                }));
            }
        }
        #region Properties Section
        private QLTBEntities db = new QLTBEntities();
        #endregion

        #region Views Section
        public ViewResult Index()
        {
            DMNNDScreenClient screen = new DMNNDScreenClient();
            if (Session[SessionScreenContansts.DanhMucNhomNguoiDung_SCREENCLIENT] != null) {
                screen = (DMNNDScreenClient)Session[SessionScreenContansts.DanhMucNhomNguoiDung_SCREENCLIENT];
            }
            Search(screen);
            return View(screen);
        }
        [HttpPost]
        public ActionResult Index (DMNNDScreenClient screen) {
            Search(screen);
            return View(screen);
        }

        [GridAction]
        public ActionResult _Index () {
            DMNNDScreenClient screen = new DMNNDScreenClient();
            if (Session[SessionScreenContansts.DanhMucNhomNguoiDung_SCREENCLIENT] != null) {
                screen = (DMNNDScreenClient)Session[SessionScreenContansts.DanhMucNhomNguoiDung_SCREENCLIENT];
            }
            Search(screen);
            return View(new GridModel(screen.DSNhomNguoiDung));
        }
        public ActionResult Create()
        {
            Models.BaseClient.DanhMucNhomNguoiDung nnd = new Models.BaseClient.DanhMucNhomNguoiDung() { IdentityNhomNguoiDung = -1 };
            return View(nnd);
        }

        public ActionResult ShowPdf()
        {
            ReportClass rpt = new ReportClass();
            rpt.FileName = Server.MapPath("~/") + "//Reports//rDanhMucNhomNguoiDung.rpt";
            rpt.SetDatabaseLogon("sa", "sa");
            rpt.Load();
            //rpt.SetDataSource(db.DanhMucNhomNguoiDungs);
            Stream stream = rpt.ExportToStream(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat);
            return File(stream, "application/pdf");
        }

        public FileResult ExportToExcel()
        {

            DataTable myTable = new DataTable();

            var data = from n in db.DanhMucNhomNguoiDungs
                       select n;

            myTable.Columns.Add("Mã Nhóm Người Dùng");
            myTable.Columns.Add("Tên Nhóm Người Dùng");
            myTable.Columns.Add("Quyền");

            foreach (var n in data)
            {
                myTable.Rows.Add(n.MaNhomNguoiDung.ToString(), n.TenNhomNguoiDung.ToString(), n.Quyen);
            }

            Response.ContentType = "application/csv";
            Response.Charset = "";
            Response.AddHeader("Content-Disposition", "attachment;filename=" + "BaoCaoDanhMucNhomNguoiDung.xls");
            Response.ContentEncoding = Encoding.Unicode;
            Response.BinaryWrite(Encoding.Unicode.GetPreamble());

            try
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("DANH MỤC NHÓM NGƯỜI DÙNG\t\t\t\n\n");
                for (int count = 0; count < myTable.Columns.Count; count++)
                {
                    if (myTable.Columns[count].ColumnName != null)
                        sb.Append(myTable.Columns[count].ColumnName);
                    if (count < myTable.Columns.Count - 1)
                        sb.Append("\t");
                }

                Response.Write(sb.ToString() + "\n");
                Response.Flush();
                int soDem = 0;
                while (myTable.Rows.Count >= soDem + 1)
                {
                    sb = new StringBuilder();
                    for (int col = 0; col < myTable.Columns.Count - 1; col++)
                    {
                        if (myTable.Rows[soDem][col] != null)
                            sb.Append(myTable.Rows[soDem][col].ToString().Replace(",", " "));
                        sb.Append("\t");
                    }
                    if (myTable.Rows[soDem][myTable.Columns.Count - 1] != null)
                        sb.Append(myTable.Rows[soDem][myTable.Columns.Count - 1].ToString().Replace(",", " "));
                    Response.Write(sb.ToString() + "\n");
                    Response.Flush();
                    soDem = soDem + 1;
                }
            }
            catch
            {

            }

            myTable.Dispose();
            Response.End();
            return File("BaoCaoDanhMucNhomNguoiDung", "application/ms-excel", "BaoCaoDanhMucNhomNguoiDung.xls");
        }

        public ActionResult XoaNhomNguoiDung()
        {
            string id = Request.QueryString["id"];
            //DanhMucNhomNguoiDung nd = db.DanhMucNhomNguoiDungs.Single(i => i.IdentityNguoiDung == checkedRecord);
            try
            {
                if (id != null)
                {
                    int iden = Convert.ToInt32(id);
                    DanhMucNhomNguoiDung nd = db.DanhMucNhomNguoiDungs.Single(i => i.IdentityNhomNguoiDung == iden);
                    db.DanhMucNhomNguoiDungs.DeleteObject(nd);
                    db.SaveChanges();
                    return RedirectToAction("Index");

                }
                else
                {
                    return RedirectToAction("Index");
                }
            }
            catch
            {
                return RedirectToAction("Index");
            }
        }

        public ActionResult SuaNhomNguoiDung()
        {
            string id = Request.QueryString["id"];
            if (id != null)
            {
                int iden = Convert.ToInt32(id);
                DanhMucNhomNguoiDung nnd = db.DanhMucNhomNguoiDungs.Single(i => i.IdentityNhomNguoiDung == iden);
                Models.BaseClient.DanhMucNhomNguoiDung nndC = new Models.BaseClient.DanhMucNhomNguoiDung();
                ObjectHelper.Copy(nnd, nndC);
                return View(nndC);

            }
            else
            {
                return RedirectToAction("Index");
            }
        }
        #endregion

        #region CRUD Section
        [HttpPost]
        public ActionResult SuaNhomNguoiDung(Models.BaseClient.DanhMucNhomNguoiDung nndC)
        {
            if (ModelState.IsValid)
            {
                //code de luu lai
                DanhMucNhomNguoiDung h = db.DanhMucNhomNguoiDungs.Single(i => i.IdentityNhomNguoiDung == nndC.IdentityNhomNguoiDung);
                if (nndC.MaNhomNguoiDung != h.MaNhomNguoiDung) {
                    if (db.DanhMucNhomNguoiDungs.Count(i => i.MaNhomNguoiDung == nndC.MaNhomNguoiDung) > 0) {
                        ViewData[qltscd.Contansts.SessionConstants.ERROR_MESSAGE] = "Mã " + nndC.MaNhomNguoiDung + " đã tồn tại";
                        return View(nndC);
                    }
                }
                ObjectHelper.Copy(nndC, h);
                db.ObjectStateManager.ChangeObjectState(h, EntityState.Modified);
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(nndC);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        [GridAction]
        public ActionResult _SaveBatchEditing([Bind(Prefix = "inserted")]IEnumerable<qltscd.Models.BaseClient.DanhMucNhomNguoiDung> inserted,
            [Bind(Prefix = "updated")]IEnumerable<qltscd.Models.BaseClient.DanhMucNhomNguoiDung> updated,
            [Bind(Prefix = "deleted")]IEnumerable<qltscd.Models.BaseClient.DanhMucNhomNguoiDung> deleted)
        {
            if (inserted != null)
            {
                foreach (var userClient in inserted)
                {
                    DanhMucNhomNguoiDung user = new DanhMucNhomNguoiDung();
                    userClient.MaNhomNguoiDung = DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString() + DateTime.Now.Millisecond.ToString();
                    ObjectHelper.Copy(userClient, user);
                    db.DanhMucNhomNguoiDungs.AddObject(user);
                }
            }
            if (updated != null)
            {
                foreach (var userClient in updated)
                {
                    DanhMucNhomNguoiDung user = db.DanhMucNhomNguoiDungs.Single(i => i.IdentityNhomNguoiDung == userClient.IdentityNhomNguoiDung);
                    ObjectHelper.Copy(userClient, user);
                    db.ObjectStateManager.ChangeObjectState(user, EntityState.Modified);
                }
            }
            if (deleted != null)
            {
                foreach (var userClient in deleted)
                {
                    DanhMucNhomNguoiDung user = db.DanhMucNhomNguoiDungs.Single(i => i.IdentityNhomNguoiDung == userClient.IdentityNhomNguoiDung);
                    db.DanhMucNhomNguoiDungs.DeleteObject(user);
                }
            }
            db.SaveChanges();
            DMNNDScreenClient screen = (DMNNDScreenClient)Session[SessionScreenContansts.DanhMucNhomNguoiDung_SCREENCLIENT];
            Search(screen);
            return View(new GridModel(screen.DSNhomNguoiDung));
        }

        [HttpPost]
        public ActionResult Create(Models.BaseClient.DanhMucNhomNguoiDung danhmucnhomnguoidung)
        {
            DanhMucNhomNguoiDung nnd = new DanhMucNhomNguoiDung();
            if (ModelState.IsValid)
            {
                if (danhmucnhomnguoidung.IdentityNhomNguoiDung == -1)
                {
                    //danhmucnhomnguoidung.MaNhomNguoiDung = DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString() + DateTime.Now.Millisecond.ToString();
                    if (danhmucnhomnguoidung.MaNhomNguoiDung != nnd.MaNhomNguoiDung)
                    {
                        if (db.DanhMucNhomNguoiDungs.Count(o => o.MaNhomNguoiDung == danhmucnhomnguoidung.MaNhomNguoiDung) > 0)
                        {
                            ViewData[SessionConstants.ERROR_MESSAGE] = "Mã nhóm người dùng " + danhmucnhomnguoidung.MaNhomNguoiDung + " đã tồn tại";
                            return View(danhmucnhomnguoidung);
                        }
                    }

                    if (danhmucnhomnguoidung.TenNhomNguoiDung != nnd.TenNhomNguoiDung)
                    {
                        if (db.DanhMucNhomNguoiDungs.Count(o => o.TenNhomNguoiDung == danhmucnhomnguoidung.TenNhomNguoiDung) > 0)
                        {
                            ViewData[SessionConstants.ERROR_MESSAGE] = "Tên nhóm người dùng " + danhmucnhomnguoidung.MaNhomNguoiDung + " đã tồn tại";
                            return View(danhmucnhomnguoidung);
                        }
                    }

                    ObjectHelper.Copy(danhmucnhomnguoidung, nnd);
                    db.DanhMucNhomNguoiDungs.AddObject(nnd);
                }
                else
                {
                    nnd = db.DanhMucNhomNguoiDungs.Single(i => i.IdentityNhomNguoiDung == danhmucnhomnguoidung.IdentityNhomNguoiDung);
                    if (danhmucnhomnguoidung.MaNhomNguoiDung != nnd.MaNhomNguoiDung)
                    {
                        if (db.DanhMucNhomNguoiDungs.Count(o => o.MaNhomNguoiDung == danhmucnhomnguoidung.MaNhomNguoiDung) > 0)
                        {
                            ViewData[SessionConstants.ERROR_MESSAGE] = "Mã nhóm người dùng " + danhmucnhomnguoidung.MaNhomNguoiDung + " đã tồn tại";
                            return View(danhmucnhomnguoidung);
                        }
                    }

                    if (danhmucnhomnguoidung.TenNhomNguoiDung != nnd.TenNhomNguoiDung)
                    {
                        if (db.DanhMucNhomNguoiDungs.Count(o => o.TenNhomNguoiDung == danhmucnhomnguoidung.TenNhomNguoiDung) > 0)
                        {
                            ViewData[SessionConstants.ERROR_MESSAGE] = "Tên nhóm người dùng " + danhmucnhomnguoidung.MaNhomNguoiDung + " đã tồn tại";
                            return View(danhmucnhomnguoidung);
                        }
                    }

                    ObjectHelper.Copy(danhmucnhomnguoidung, nnd);
                    db.ObjectStateManager.ChangeObjectState(nnd, EntityState.Modified);
                }
                db.SaveChanges();
                return RedirectToAction("create");
            }
            return View(danhmucnhomnguoidung);
        }
        #endregion

        #region Helper Section
        private void Search (DMNNDScreenClient screen) {
            if (Session[SessionScreenContansts.DanhMucNhomNguoiDung_SCREENCLIENT] != null) {
                screen = (DMNNDScreenClient)Session[SessionScreenContansts.DanhMucNhomNguoiDung_SCREENCLIENT];
            } else {
                screen = new DMNNDScreenClient();
            }
            screen.DSNhomNguoiDung.Clear();
            var list = db.DanhMucNhomNguoiDungs.OrderBy(i => i.TenNhomNguoiDung).ToList();
            foreach (DanhMucNhomNguoiDung DMNND in list) {
                qltscd.Models.BaseClient.DanhMucNhomNguoiDung DMNNDClient = new Models.BaseClient.DanhMucNhomNguoiDung();
                ObjectHelper.Copy(DMNND, DMNNDClient);
                screen.DSNhomNguoiDung.Add(DMNNDClient);
            }
            Session[SessionScreenContansts.DanhMucNhomNguoiDung_SCREENCLIENT] = screen;
        }
        #endregion

        #region Additional Section
        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
        #endregion
    }
}
